// pages/poster/poster.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import dataJson from '../../data'
import init from './init'

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    infoList: [],
    initData: init,
    shareImage: '',
    painting: dataJson
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '海报生成中...',
    })
    let itemList = app.globalData.form;
    if(typeof(options.data) != 'undefined'){
      itemList = JSON.parse(options.data);
    }
    let editData = this.data.painting;
    if(typeof(options.painting) != 'undefined') {
      editData = JSON.parse(options.painting);
    }
    // let editData = this.data.painting;
    this.update(itemList, editData);
  },
  watch:{
    painting:function(newValue){
        console.log(newValue); // name改变时，调用该方法输出新值。
    }
  },
  update: function(itemList, jsonData){
    let initData = this.data.initData;
    itemList.forEach(d => {
      const value = d.value;
      const id = d.id;
      jsonData.views.forEach(json => {
        const postName = json.name;
        if (id == postName && json.type == 'image'){
          json.url = value;
          initData.views.push(json)
        }else if(id == postName && json.type == 'text'){
          json.content = value;
          initData.views.push(json);
        }
      })
    });
    this.setData({
      painting: initData,
      initData: init
    })
  },
  edit: function(){
    const data = this.data.painting;
    console.log(data)
    wx.redirectTo({
      url: '../edit/edit?data='+JSON.stringify(data),
    })
  },
  eventSave () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImage,
      success (res) {
        wx.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 1000
        })
      },
      fail: function(res){
        if(res.errMsg.indexOf("auth") > 0 && res.errMsg.indexOf("deny") > 0) {
          wx.showModal({
            title: '提示',
            content: '是否授权保存图片到相册',
            success (res) {
              if (res.confirm) {
                wx.openSetting({
                  success (res) {
                  }
                })
              } else if (res.cancel) {
                wx.showToast({
                  title: '很遗憾无法保存图片到本地',
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }
      },
      complete:function(res){
        console.log("complete:" + res)
      }
    })
  },
  eventGetImage: function (event) {
    wx.hideLoading()
    console.log(this.data.painting)
    const { tempFilePath, errMsg } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
  }
})